package net.comm.util;

import java.sql.Connection;   
import java.sql.DriverManager;   
import java.sql.SQLException;   
import java.util.HashMap;   
import java.util.List;   
import java.util.Map;   
  
import org.apache.commons.dbcp.ConnectionFactory;   
import org.apache.commons.dbcp.DriverManagerConnectionFactory;   
import org.apache.commons.dbcp.PoolableConnectionFactory;   
import org.apache.commons.dbcp.PoolingDriver;   
import org.apache.commons.pool.ObjectPool;   
import org.apache.commons.pool.impl.GenericObjectPool;   
  
  
public class DbcpPool {   
    public static void main(String[] args) {   
  
    }   
  
    private static String dbJdbc = null;   
  
    private static String dbUser = null;   
  
    private static String dbPwd = null;   
  
    private static int max;   
  
    private static long wait;   
  
    private static String driver = null;   
  
    private static Class driverClass = null;   
  
    private static ObjectPool connectionPool = null;   
  
    public static Map<String, ObjectPool> map = null;   
  
    public DbcpPool(){ 
    	
    }   
  
    /** *//**  
     * 初始化数据源  
     */  
    private static synchronized void initDataSource() {   
        // 驱动数据源   
        if (driverClass == null) {   
            try {   
                driverClass = Class.forName(driver);   
            } catch (ClassNotFoundException e) {   
                e.printStackTrace();   
            }   
        }   
    }   
  
    /** *//**  
     * 连接池启动  
     *   
     * @throws Exception  
     */  
    public static void StartPool(String poolname, String dbJdbc, String dbUser,   
            String dbPwd, int max, long wait) {   
        // 初始化数据源   
        initDataSource();   
        // 如果连接池为空   
        if (connectionPool != null) {   
            ShutdownPool();   
        }   
        try {   
            connectionPool = new GenericObjectPool(null, max, (byte) 1, wait);   
            ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(   
                    dbJdbc, dbUser, dbPwd);   
            PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(   
                    connectionFactory, connectionPool, null, null, false, true);   
            Class.forName("org.apache.commons.dbcp.PoolingDriver");   
            PoolingDriver driver = (PoolingDriver) DriverManager   
                    .getDriver("jdbc:apache:commons:dbcp:");   
            driver.registerPool(poolname, connectionPool);   
            
            map.put(poolname, connectionPool);   
//            System.out.println("Create " + poolname   
//                    + " for Database Connection Succees.");   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
  
    /** *//**  
     * 释放连接池  
     */  
    public static void ShutdownPool() {   
        try {   
            PoolingDriver driver = (PoolingDriver) DriverManager   
                    .getDriver("jdbc:apache:commons:dbcp:");   
            driver.closePool("dbpool");   
        } catch (SQLException e) {   
            e.printStackTrace();   
        }   
    }   
  
    /** *//**  
     * 打印连接池状态  
     */  
    public static String GetPoolStats(String poolname) {   
  
        StringBuffer stat = new StringBuffer();   
        try {   
            PoolingDriver driver = (PoolingDriver) DriverManager   
                    .getDriver("jdbc:apache:commons:dbcp:");   
            ObjectPool connectionPool = driver.getConnectionPool(poolname);   
  
            stat.append("-- Active Connection: ");   
            stat.append(connectionPool.getNumActive());   
            stat.append(" ,");   
            stat.append("Free Connection: ");   
            stat.append(connectionPool.getNumIdle());   
            stat.append(" . --");   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
        return stat.toString();   
    }   
  
    /** *//**  
     * 取得连接池中的连接  
     *   
     * @return  
     */  
    public synchronized static Connection getConnection(String poolname) {   
        Connection conn = null;   
        if (map == null) {   
            map = new HashMap<String, ObjectPool>();   
        }   
        if (map.get(poolname) == null) {   
            init(poolname);// 初始化基本数据   
            StartPool(poolname, dbJdbc, dbUser, dbPwd, max, wait);   
        }   
        try {   
            conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:"  
                    + poolname);   
        } catch (SQLException e) {   
            e.printStackTrace();   
        }   
        return conn;   
    }   
    /** *//**  
     * 取得连接池中的连接  
     *   
     * @return  
     */  
    public synchronized static Connection getConnection() {   
        Connection conn = null;   
        if (map == null) {   
            map = new HashMap<String, ObjectPool>();   
        }   
        if (map.get("one") == null) {   
            init("one");// 初始化基本数据   
            StartPool("one", dbJdbc, dbUser, dbPwd, max, wait);   
        }   
        try {   
            conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:"  
                    + "one");   
        } catch (SQLException e) {   
            e.printStackTrace();   
        }   
        return conn;   
    }  
    
    private static void init(String poolname) {   
        List<BaseConnBean> pools = ConfigXml.read();   
        for (BaseConnBean baseConnBean : pools) {   
            if (baseConnBean.getName().equals(poolname)) {   
                dbJdbc = baseConnBean.getJdbcurl();   
                dbUser = baseConnBean.getUsername();   
                dbPwd = baseConnBean.getPassword();   
                max = baseConnBean.getMax();   
                wait = baseConnBean.getWait();   
                driver = baseConnBean.getDriver();   
            }   
  
        }   
    }   
  
    public static void close(Connection c) {   
        try {   
            if (c != null)   
                c.close();   
        } catch (SQLException e) {   
            e.printStackTrace();   
        }   
    }   
  
	/**
	 * 开启事务
	 * @param cn
	 * @throws SQLException
	 */
	public static void beginTran(Connection cn)
	{
		try
		{
			if(cn != null && !cn.isClosed()) {
			    cn.setAutoCommit(false);
		    }
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 关闭事务
	 * @param cn
	 * @throws SQLException
	 */
	public static void closeTran(Connection cn) throws Exception
	{
		if( cn != null && !cn.isClosed())
		{
			cn.setAutoCommit(true);
		}
	}

	
	/**
	 * 提交事务
	 * @param cn
	 * @throws Exception
	 */
	public static void commitTran(Connection cn) throws Exception
	{
		if( cn != null && !cn.isClosed()&& !cn.getAutoCommit() )
		{
			cn.commit();
		}
	}

	
	/**
	 * 回滚事务
	 * @param cn
	 * @throws SQLException
	 */
	public static void rollBackTran(Connection cn) throws Exception
	{
		if( cn != null && !cn.isClosed()&& !cn.getAutoCommit())
		{
			cn.rollback();
		}
	}
	    
	/**
	 * 关闭连接
	 * @param con
	 */
	public static void returnConnection(Connection con) 
	{
		try 
		{
			if(con!=null && !con.isClosed()) 
			{
				if(!con.getAutoCommit()) 
				{
					con.rollback();		
					con.setAutoCommit(true);
				}

				if(con!=null) {
				    con.close();
				}
			}						

		}catch(SQLException sqlE) 
		{
			sqlE.printStackTrace();

		}catch (Exception ex) 
		{
			ex.printStackTrace();

	    }
	}    
    
}  
